// 路由
import LayoutView from "../views/layout/LayoutView.vue";
import { createWebHistory } from "vue-router";
import { createRouter } from "vue-router";

import HomeView from "../views/home/HomeView.vue";
import SignPending from "../views/sign/pending/SignPending.vue";
import LoginView from "../views/login/LoginView.vue";
import { useRouter } from "vue-router";
import { useGlobalStore } from "../store/global";
import MedicineAdd from "../views/medicine/MedicineAdd.vue";



// 懒加载
const NotFound = () => import('@/views/404/NotFound.vue');



// 以对象的形式，获取到views目录下所有的.vue的文件
const modules = import.meta.glob("../views/**/*.vue");


// routes项目中所有页面的路由配置
const routes = [
  { path: '/', redirect: '/home' },
  {
    // 布局页的路由
    path: '/',
    component: LayoutView,
    name: 'LayoutView',
    // redirect: '/admin/index',
    // children: [
    //   {
    //     path: 'data/MedicineAdd/add',
    //     component: MedicineAdd,


    //   },
    //   {
    //     path: 'data/team/list',
    //     component: TeamManage,

    //   },
    //   {
    //     path: 'data/doctor/list',
    //     component: DoctorManage,

    //   },
    //   {
    //     path: 'setting/role/list',
    //     component: RoleManage,

    //   },
    //   {
    //     path: 'home',
    //     component: HomeView,

    //   },
    //   {
    //     path: 'sign/pending',
    //     component: SignPending

    //   },

    // ]
  },
  { path: '/login', component: LoginView },
  { path: '/:pathMatch(.*)*', component: NotFound }
]


const router = createRouter({
  // 设置路由模式（history模式）
  history: createWebHistory(),
  // 配置路由对象（设置路径URL和组件之间的关联关系）
  routes: routes
})



// 路由白名单(不需要登录也可以访问)
const WHITE_LIST = ['/login'];

// 全局前置守卫
router.beforeEach(async (to) => {
  // 获取用户token
  const token = localStorage.doctor_token;
  // 如果token存在同时前往登录页
  if (token && to.path == '/login') {
    return '/home'
  }
  // 如果没有token进入系统页面
  if (!token) {
    if (!WHITE_LIST.includes(to.path)) {
      return '/login'
    }
  }

  const globalStore = useGlobalStore()
  await globalStore.getInfoByToken()
  const permissionData = globalStore.permissionData
  console.log(permissionData);
  console.log(globalStore.doctorInfo);

  if (permissionData) {
    if (router.getRoutes().length == routes.length) {
      addRoute(permissionData)
      return to;
    }
  }

})

export function toLogin() {
  router.replace('/login');
  // localStorage.clear();  // 清空localStorage
  localStorage.removeItem('doctor_token');  // 删除admin_token
}

function addRoute(data) {
  data.forEach(item => {
    if (item.component_path) {
      router.addRoute('LayoutView', {
        path: item.route_path,
        component: modules[`../views${item.component_path}.vue`]
      })
    }
    if (item.children) {
      addRoute(item.children)
    }
  })
}

export function registerRouter(app) {
  app.use(router);
}